package tv.geir.slackspace.util;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PrimitiveUtil {

	private static Log log = LogFactory.getLog( PrimitiveUtil.class );
    
    /**
     * A map that holds default values for all primitives. A primitive's
     * canonical name is used as key to store the value
     *  
     */
    private static transient Map<String, Object> primitives;

    
    static {
        primitives = new HashMap<String, Object>();

        primitives.put("short", (short) 0);
        primitives.put("char", (char) 0);
        primitives.put("int", (int) 0);
        primitives.put("long", (long) 0);
        primitives.put("double", (double) 0);
        primitives.put("float", (float) 0);

        primitives.put("java.lang.Short", (short) 0);
        primitives.put("java.lang.Character", (char) 0);
        primitives.put("java.lang.Integer", (int) 0);
        primitives.put("java.lang.Long", (long) 0);
        primitives.put("java.lang.Double", (double) 0);
        primitives.put("java.lang.Float", (float) 0);
    }
    
    /**
     * Returns true if <code>value</code> is an a primitive and it holds 
     * the default value for that type.
     * @param value
     * @return
     */
    public boolean isPrimitiveWithDefaultValue(Object value) {
        String cName = value.getClass().getName();
        Object primitiveDefaultValue = primitives.get(cName);
        if (primitiveDefaultValue == null) {
            // non-primitive
            if (log.isDebugEnabled() ) {
				log.debug("Not a primitive: "
                        + value.getClass().getName());
            }
            return false;
        }
        if (primitiveDefaultValue.equals(value)) {
            // primitive with default value
            if (log.isDebugEnabled() ) {
				log.debug("Primitive with default name: " + value);
            }            
            return true;
        }
        // primitive with non-default value
        if (log.isDebugEnabled() ) {
			log.debug("Primitive with non-default value: " + value);
        }
        return false;
    }

}
